package com.gitee.liuzhi.common.util;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @Author liuzhi
 * @Date 2023/8/29 22:10
 * @Version 1.0
 * @Description 线程本地缓存
 */
public class ScopeCacheUtil {

    //缓存的数据 注意：使用完后记得删除
    //InheritableThreadLocal 这个可以在子线程中使用
    private static final ThreadLocal<ConcurrentMap<String, Object>> data = ThreadLocal.withInitial(ConcurrentHashMap::new);

    public static Object remove(String name) {
        return data.get().remove(name);
    }

    public static void clearContext() {
        data.remove();
    }

    @SuppressWarnings("unchecked")
    public static <T> T get(String name) {
        return (T)data.get().get(name);
    }

    public static Object put(String name, Object value) {
        if (value != null) {
            Object result = data.get().put(name, value);
            return result != null ? result : value;
        }
        return null;
    }

    public static Object putIfAbsent(String name, Object value) {
        if (value != null) {
            Object result = data.get().putIfAbsent(name, value);
            return result != null ? result : value;
        }
        return null;
    }

}
